<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/29 14:22
 * Remark:
 */

namespace App\Http\Middleware\AdminAuth;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\AdminTokenFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Log\AdminOperationLogModel;
use App\Models\Log\OperationLogModel;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class AdminRequestMiddleware
{

    private function gl($permitPath,$request){
        foreach($permitPath as $value){
            if(strstr($request->path(),$value)){
                return true;
            }
        }
        return false;
    }

    public function handle($request, Closure $next)
    {
        // 允许通过的路由
        $permitPath = ['adx/login'];
        if(!($this->gl($permitPath,$request))){
            $adminLoginFunc= new AdminTokenFunc();
            $adminLoginInfo = $adminLoginFunc->getUkTInfo();
            if(isset($adminLoginInfo['error'])){
                throw new HttpResponseException( ResponseFunc::returnJson(
                    'error',
                    null,
                    "登录失效 ex:".$adminLoginInfo['error'],
                    401,
                ));
            }
            $input = $request->all(); //操作的内容
            $path = $request->path();  //操作的路由
            $method = $request->method();  //操作的方法
            $ip = $request->ip();  //操作的IP

            self::writeLog($adminLoginInfo['admin_id'],$input,$path,$method,$ip);
        }
        return $next($request);
    }

    public  function writeLog($userId,$input,$path,$method,$ip){
        $log = new AdminOperationLogModel();
        $log->setAttribute('user_id', $userId);
        $log->setAttribute('path', $path);
        $log->setAttribute('method', $method);
        $log->setAttribute('ip', $ip);
        $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE));
        $log->save();
    }
}